<template>
  <div class="login">
    <el-form
      :rules="rules"
      class="login-form"
      ref="form"
      :model="form"
      label-width="80px"
      label-position="top"
    >
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
        v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
        class="login-btn" type="primary" @click="onSubmit"
          :loading="isLoginLoading"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { Form } from 'element-ui'
import { login } from '@/services/user'
export default Vue.extend({
  name: 'Login',
  data () {
    return {
      isLoginLoading: false,
      form: {
        phone: '15510792995',
        password: '111111'
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async onSubmit () {
      this.isLoginLoading = true
      try {
      // 1. 表单验证
        await (this.$refs.form as Form).validate()
        // 2. 验证通过- 提交表单
        // 3. 处理请求结果

        // const { data } = await request({
        //   method: 'POST',
        //   url: '/front/user/login',
        //   headers: { 'content-type': 'application/x-www-form-urlencoded' },
        //   data: qs.stringify(this.form) // axios 默认发送的 application/json格式的数据
        // })

        const { data } = await login(this.form)

        console.log(data)
        if (data.state !== 1) {
          this.$message.error(data.message)
        } else {
          try {
            this.$store.commit('setUser', data.content)
          } catch (err) {

          }
          // 成功 跳转到首页
          this.$router.push(this.$route.query.redirect as string || '/')
          this.$message.success('登录成功')
        }
        this.isLoginLoading = false
      } catch (err) {
        this.isLoginLoading = false
      }
    }
  }
})
</script>

<style lang="scss" scoped>
.login {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  .login-form {
    background-color: #fff;
    padding: 20px;
    border-radius: 5px;
    width: 300px;
  }
  .login-btn {
    width: 100%;
  }
}
</style>
